import {render as sidebarRender,afterRender as sidebarAfterRender} from "./+sidebar.js";
import {render as navbarRender ,afterRender as navbarAfterRender} from "./+navbar.js";
import {render as pagecardRender,afterRender as pagecardAfterRender} from "./+pagecard.js";
import {EventBus} from "../eventbus.js";
import {Router} from "../routesystem.js";
import {store1} from "../store.js";

export var name = "+layout";

export function render() {
  return `
    <style>
      .main-content {
        position: fixed;
        top: 0;
        right: 0;
        width: 85%;
        height: 100%;
        background: #f8f9fa;
      }

      .breadcrumb-nav {
        background-color: #ffffff;
        padding: 0.5rem 1rem;
        border-bottom: 1px solid #e9ecef;
        margin-bottom: 1rem;
      }
   

      @media (max-width: 992px) {
        .main-content {
          position: fixed;
          top: 0;
          right: 0;
          width: 100%;
          height: 100%;
          background: #f8f9fa;
        }
      }
    </style>
  
    <div class="app-container">
      ${sidebarRender()}
  
      <!-- 主内容区 -->
      <main class="main-content">
  
        <!-- 顶部导航栏 -->
        ${navbarRender()}
        <!-- 卡片导航栏 -->
        ${pagecardRender()}
        
  
        <!-- 页面内容容器 -->
        <div id="content" class="page-content"></div>
      </main>
    </div>
  `;
}

export  function afterRender() {

  //加载事件
  async function loadEvent(){
      var hash = location.hash.slice(1) || store1.state.activeMenu;
      var contentDiv = document.getElementById("content");
  
      //对象?.属性    左边的对象如果为null或undedined  则 右边不执行
      var module = await Router.routes[hash]?.();
  
      if(module && module.render){
          var html = module.render();
          if(html){
              contentDiv.innerHTML = html;
  
              if(module.afterRender){
                  module.afterRender();
              }
  
          }else{
              EventBus.emit("route:404","<h1>404 Not Found</h1>");
          }
          // 触发组件渲染事件
          EventBus.emit("component:rendered", module.name || "Unknown");
          // 触发路由变化事件
          EventBus.emit("route:change", {path:hash});
      }else{
          contentDiv.innerHTML = "<h1>组件加载失败</h1>"
      }
  }

  loadEvent();

  window.addEventListener("hashchange", loadEvent);

  //================================================
  sidebarAfterRender();
  navbarAfterRender();
  pagecardAfterRender();

}